<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AugmentOS Camera Server</title>
    <style>
      :root {
        --primary-color: #3498db;
        --secondary-color: #2980b9;
        --success-color: #2ecc71;
        --warning-color: #f39c12;
        --error-color: #e74c3c;
        --background-color: #f8f9fa;
        --card-background: #ffffff;
        --text-color: #2c3e50;
        --border-color: #e9ecef;
        --shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        --border-radius: 12px;
      }

      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: var(--text-color);
        line-height: 1.6;
        min-height: 100vh;
      }

      .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
      }

      .header {
        text-align: center;
        margin-bottom: 30px;
        color: white;
      }

      .header h1 {
        font-size: 2.5rem;
        font-weight: 300;
        margin-bottom: 10px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
      }

      .header p {
        font-size: 1.1rem;
        opacity: 0.9;
      }

      .server-info {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        border-radius: var(--border-radius);
        padding: 15px;
        margin-bottom: 30px;
        color: white;
        text-align: center;
      }

      .server-url {
        font-family: "Courier New", monospace;
        background: rgba(0, 0, 0, 0.2);
        padding: 8px 12px;
        border-radius: 6px;
        margin: 10px 0;
        display: inline-block;
      }

      .main-content {
        display: grid;
        grid-template-columns: 1fr 2fr;
        gap: 30px;
        margin-bottom: 30px;
      }

      .camera-panel {
        background: var(--card-background);
        border-radius: var(--border-radius);
        padding: 25px;
        box-shadow: var(--shadow);
        height: fit-content;
      }

      .camera-panel h2 {
        color: var(--primary-color);
        margin-bottom: 20px;
        font-weight: 600;
      }

      .capture-button {
        width: 100%;
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        color: white;
        border: none;
        padding: 15px 20px;
        font-size: 1.1rem;
        border-radius: var(--border-radius);
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        font-weight: 500;
      }

      .capture-button:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(52, 152, 219, 0.3);
      }

      .capture-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
      }

      .camera-icon {
        width: 24px;
        height: 24px;
      }

      .status-indicator {
        margin-top: 20px;
        padding: 15px;
        border-radius: var(--border-radius);
        text-align: center;
        font-weight: 500;
      }

      .status-success {
        background: rgba(46, 204, 113, 0.1);
        color: var(--success-color);
        border: 1px solid rgba(46, 204, 113, 0.2);
      }

      .status-loading {
        background: rgba(52, 152, 219, 0.1);
        color: var(--primary-color);
        border: 1px solid rgba(52, 152, 219, 0.2);
      }

      .status-error {
        background: rgba(231, 76, 60, 0.1);
        color: var(--error-color);
        border: 1px solid rgba(231, 76, 60, 0.2);
      }

      .gallery-panel {
        background: var(--card-background);
        border-radius: var(--border-radius);
        padding: 25px;
        box-shadow: var(--shadow);
      }

      .gallery-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }

      .gallery-header h2 {
        color: var(--primary-color);
        font-weight: 600;
      }

      .refresh-button {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 0.9rem;
        transition: all 0.3s ease;
      }

      .refresh-button:hover {
        background: var(--secondary-color);
      }

      .gallery-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 20px;
      }

      .photo-card {
        background: white;
        border-radius: var(--border-radius);
        overflow: hidden;
        box-shadow: var(--shadow);
        transition: all 0.3s ease;
        cursor: pointer;
        position: relative;
      }

      .photo-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
      }

      .photo-image {
        width: 100%;
        height: 150px;
        object-fit: cover;
        background: #f8f9fa;
      }

      .video-indicator {
        position: absolute;
        top: 10px;
        right: 10px;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.7rem;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 4px;
      }

      .video-indicator svg {
        width: 12px;
        height: 12px;
      }

      .file-type-badge {
        position: absolute;
        top: 10px;
        left: 10px;
        background: rgba(52, 152, 219, 0.9);
        color: white;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 0.6rem;
        font-weight: 600;
        text-transform: uppercase;
      }

      .file-type-badge.video {
        background: rgba(231, 76, 60, 0.9);
      }

      .photo-info {
        padding: 15px;
      }

      .photo-name {
        font-weight: 600;
        margin-bottom: 8px;
        color: var(--text-color);
        font-size: 0.9rem;
      }

      .photo-meta {
        font-size: 0.8rem;
        color: #6c757d;
        margin-bottom: 10px;
      }

      .photo-actions {
        display: flex;
        gap: 8px;
      }

      .action-button {
        flex: 1;
        padding: 6px 12px;
        border: none;
        border-radius: 4px;
        font-size: 0.8rem;
        cursor: pointer;
        transition: all 0.3s ease;
      }

      .view-button {
        background: var(--primary-color);
        color: white;
      }

      .download-button {
        background: var(--success-color);
        color: white;
      }

      .action-button:hover {
        opacity: 0.8;
        transform: translateY(-1px);
      }

      .loading-spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 1s ease-in-out infinite;
      }

      @keyframes spin {
        to {
          transform: rotate(360deg);
        }
      }

      .empty-gallery {
        text-align: center;
        padding: 40px;
        color: #6c757d;
      }

      .empty-gallery svg {
        width: 64px;
        height: 64px;
        margin-bottom: 20px;
        opacity: 0.5;
      }

      .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.8);
        backdrop-filter: blur(5px);
      }

      .modal-content {
        position: relative;
        margin: 5% auto;
        max-width: 90%;
        max-height: 90%;
        background: white;
        border-radius: var(--border-radius);
        overflow: hidden;
      }

      .modal-image {
        width: 100%;
        height: auto;
        max-height: 80vh;
        object-fit: contain;
      }

      .modal-content {
        position: relative;
      }

      .video-thumbnail-note {
        position: absolute;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 10px 20px;
        border-radius: 20px;
        font-size: 0.9rem;
        text-align: center;
        z-index: 10;
      }

      .video-thumbnail-note a {
        color: #3498db;
        text-decoration: none;
        font-weight: bold;
      }

      .video-thumbnail-note a:hover {
        text-decoration: underline;
      }

      .modal-close {
        position: absolute;
        top: 15px;
        right: 15px;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        border: none;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        font-size: 20px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .modal-close:hover {
        background: rgba(0, 0, 0, 0.9);
      }

      .toast {
        position: fixed;
        top: 20px;
        right: 20px;
        background: var(--success-color);
        color: white;
        padding: 15px 20px;
        border-radius: var(--border-radius);
        box-shadow: var(--shadow);
        z-index: 1001;
        transform: translateX(100%);
        transition: transform 0.3s ease;
      }

      .toast.show {
        transform: translateX(0);
      }

      .toast.error {
        background: var(--error-color);
      }

      @media (max-width: 768px) {
        .main-content {
          grid-template-columns: 1fr;
          gap: 20px;
        }

        .header h1 {
          font-size: 2rem;
        }

        .gallery-grid {
          grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
          gap: 15px;
        }

        .container {
          padding: 15px;
        }
      }

      /* API Documentation Styles */
      .api-documentation {
        background: var(--card-background);
        border-radius: var(--border-radius);
        padding: 25px;
        box-shadow: var(--shadow);
        margin-top: 30px;
      }

      .api-documentation h2 {
        color: var(--primary-color);
        margin-bottom: 20px;
        font-weight: 600;
        text-align: center;
      }

      .api-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
      }

      .api-endpoint {
        background: var(--background-color);
        border-radius: var(--border-radius);
        padding: 20px;
        border-left: 4px solid var(--primary-color);
      }

      .api-endpoint h3 {
        color: var(--text-color);
        margin-bottom: 10px;
        font-weight: 600;
      }

      .api-endpoint code {
        background: var(--text-color);
        color: white;
        padding: 8px 12px;
        border-radius: 6px;
        font-family: "Courier New", monospace;
        font-size: 0.9rem;
        display: block;
        margin: 10px 0;
        word-break: break-all;
      }

      .api-endpoint p {
        color: var(--text-color);
        margin-bottom: 15px;
        line-height: 1.5;
      }

      .api-example {
        background: #f8f9fa;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        padding: 15px;
        margin-top: 15px;
      }

      .api-example strong {
        color: var(--text-color);
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
      }

      .api-example pre {
        background: var(--text-color);
        color: white;
        padding: 12px;
        border-radius: 6px;
        font-family: "Courier New", monospace;
        font-size: 0.8rem;
        overflow-x: auto;
        white-space: pre-wrap;
        word-break: break-word;
        margin: 8px 0;
      }

      @media (max-width: 768px) {
        .api-grid {
          grid-template-columns: 1fr;
        }

        .api-endpoint {
          padding: 15px;
        }

        .api-example pre {
          font-size: 0.7rem;
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h1>📸 AugmentOS Camera</h1>
        <p>Smart Glasses Photo Gallery & Capture</p>
      </div>

      <div class="server-info">
        <div>🌐 Server running on port <strong>{{SERVER_PORT}}</strong></div>
        <div class="server-url">{{SERVER_URL}}</div>
        <div>📱 Connect your mobile device to the same network to access this gallery</div>
      </div>

      <div class="main-content">
        <div class="camera-panel">
          <h2>📷 Camera Controls</h2>
          <button id="captureButton" class="capture-button" onclick="takePicture()">
            <svg class="camera-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path>
              <circle cx="12" cy="13" r="4"></circle>
            </svg>
            Take Photo
          </button>
          <div id="statusIndicator" class="status-indicator" style="display: none"></div>
        </div>

        <div class="gallery-panel">
          <div class="gallery-header">
            <h2>🖼️ Media Gallery</h2>
            <button class="refresh-button" onclick="loadGallery()">🔄 Refresh</button>
          </div>
          <div id="galleryGrid" class="gallery-grid">
            <div class="empty-gallery">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                <circle cx="8.5" cy="8.5" r="1.5"></circle>
                <polyline points="21,15 16,10 5,21"></polyline>
              </svg>
              <div>No media files yet</div>
              <div style="font-size: 0.9rem; margin-top: 10px">Take your first photo or video to get started!</div>
            </div>
          </div>
        </div>
      </div>

      <!-- API Documentation Section -->
      <div class="api-documentation">
        <h2>🔧 API Documentation</h2>
        <div class="api-grid">
          <div class="api-endpoint">
            <h3>📸 Take Picture</h3>
            <code>GET /api/take-picture</code>
            <p>Triggers photo capture on the device</p>
          </div>

          <div class="api-endpoint">
            <h3>🖼️ Latest Photo</h3>
            <code>GET /api/latest-photo</code>
            <p>Returns the most recently captured photo</p>
          </div>

          <div class="api-endpoint">
            <h3>📚 Media Gallery</h3>
            <code>GET /api/gallery</code>
            <p>Returns list of all photos and videos with metadata</p>
            <div class="api-example">
              <strong>Response includes video information:</strong>
              <pre>
{
  "photos": [
    {
      "name": "photo1.jpg",
      "is_video": false,
      "thumbnail_url": "/api/photo?file=photo1.jpg"
    },
    {
      "name": "video1.mp4",
      "is_video": true,
      "thumbnail_url": "/api/photo?file=video1.mp4"
    }
  ]
}</pre
              >
            </div>
          </div>

          <div class="api-endpoint">
            <h3>🖼️ Specific Photo/Video</h3>
            <code>GET /api/photo?file=filename.jpg</code>
            <p>Returns a specific photo or video thumbnail by filename</p>
            <div class="api-example">
              <strong>Video files return thumbnails:</strong>
              <pre>
GET /api/photo?file=video1.mp4
→ Returns JPEG thumbnail image</pre
              >
            </div>
          </div>

          <div class="api-endpoint">
            <h3>⬇️ Download Media</h3>
            <code>GET /api/download?file=filename.jpg</code>
            <p>Downloads a specific photo or video file</p>
          </div>

          <div class="api-endpoint">
            <h3>🧹 Cleanup Old Files</h3>
            <code>GET /api/cleanup?max_age_hours=24</code>
            <p>Deletes files older than specified hours (default: 24)</p>
          </div>

          <div class="api-endpoint">
            <h3>🗑️ Delete Specific Files</h3>
            <code>POST /api/delete-files</code>
            <p>Deletes specific files by name</p>
            <div class="api-example">
              <strong>Request Body:</strong>
              <pre>
{
  "files": ["photo1.jpg", "photo2.jpg", "photo3.jpg"]
}</pre
              >
              <strong>Response:</strong>
              <pre>
{
  "message": "File deletion completed",
  "total_files": 3,
  "successful_deletions": 2,
  "failed_deletions": 1,
  "total_deleted_size": 2048576,
  "results": [
    {
      "file": "photo1.jpg",
      "success": true,
      "message": "File deleted successfully",
      "size": 1024288
    }
  ]
}</pre
              >
            </div>
          </div>

          <div class="api-endpoint">
            <h3>📊 Server Status</h3>
            <code>GET /api/status</code>
            <p>Returns server status and file management metrics</p>
          </div>

          <div class="api-endpoint">
            <h3>❤️ Health Check</h3>
            <code>GET /api/health</code>
            <p>Returns server health status</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Photo Modal -->
    <div id="photoModal" class="modal">
      <div class="modal-content">
        <button class="modal-close" onclick="closeModal()">&times;</button>
        <img id="modalImage" class="modal-image" src="" alt="Photo" />
      </div>
    </div>

    <!-- Toast Notifications -->
    <div id="toast" class="toast"></div>

    <script>
      let isCapturing = false
      let currentGallery = []

      // Initialize the page
      document.addEventListener("DOMContentLoaded", function () {
        loadGallery()
        updateServerInfo()
      })

      // Update server info with actual values
      function updateServerInfo() {
        const serverUrl = window.location.origin
        const serverPort = window.location.port

        document.querySelector(".server-url").textContent = serverUrl
        document.querySelector(".server-info div:first-child").innerHTML =
          `🌐 Server running on port <strong>${serverPort}</strong>`
      }

      // Take a photo
      async function takePicture() {
        if (isCapturing) return

        const captureButton = document.getElementById("captureButton")
        const statusIndicator = document.getElementById("statusIndicator")

        isCapturing = true
        captureButton.disabled = true
        captureButton.innerHTML = '<div class="loading-spinner"></div> Capturing...'

        statusIndicator.style.display = "block"
        statusIndicator.className = "status-indicator status-loading"
        statusIndicator.textContent = "📸 Capturing photo..."

        try {
          const response = await fetch("/api/take-picture", {
            method: "POST",
          })

          if (response.ok) {
            statusIndicator.className = "status-indicator status-success"
            statusIndicator.textContent = "✅ Photo captured successfully!"

            showToast("Photo captured successfully!", "success")

            // Wait a bit for the photo to be saved, then refresh gallery
            setTimeout(() => {
              loadGallery()
            }, 2000)
          } else {
            throw new Error("Failed to capture photo")
          }
        } catch (error) {
          console.error("Error taking picture:", error)
          statusIndicator.className = "status-indicator status-error"
          statusIndicator.textContent = "❌ Failed to capture photo"
          showToast("Failed to capture photo", "error")
        } finally {
          setTimeout(() => {
            isCapturing = false
            captureButton.disabled = false
            captureButton.innerHTML = `
                        <svg class="camera-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path>
                            <circle cx="12" cy="13" r="4"></circle>
                        </svg>
                        Take Photo
                    `
            statusIndicator.style.display = "none"
          }, 3000)
        }
      }

      // Load the photo gallery
      async function loadGallery() {
        const galleryGrid = document.getElementById("galleryGrid")

        try {
          const response = await fetch("/api/gallery")
          const data = await response.json()

          if (data.status === "success") {
            currentGallery = data.data.photos
            renderGallery(data.data.photos)
          } else {
            throw new Error(data.message || "Failed to load gallery")
          }
        } catch (error) {
          console.error("Error loading gallery:", error)
          galleryGrid.innerHTML = `
                    <div class="empty-gallery">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"></path>
                        </svg>
                        <div>Error loading gallery</div>
                        <div style="font-size: 0.9rem; margin-top: 10px;">${error.message}</div>
                    </div>
                `
        }
      }

      // Render the gallery
      function renderGallery(photos) {
        const galleryGrid = document.getElementById("galleryGrid")

        if (photos.length === 0) {
          galleryGrid.innerHTML = `
                    <div class="empty-gallery">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                            <circle cx="8.5" cy="8.5" r="1.5"></circle>
                            <polyline points="21,15 16,10 5,21"></polyline>
                        </svg>
                        <div>No media files yet</div>
                        <div style="font-size: 0.9rem; margin-top: 10px;">Take your first photo or video to get started!</div>
                    </div>
                `
          return
        }

        galleryGrid.innerHTML = photos
          .map((photo, index) => {
            const isVideo = photo.is_video || false
            const fileExtension = photo.name.split(".").pop().toLowerCase()
            const isVideoByExtension = ["mp4", "avi", "mov", "wmv", "flv", "webm", "mkv", "3gp"].includes(fileExtension)
            const isVideoFile = isVideo || isVideoByExtension

            return `
                <div class="photo-card" onclick="viewPhoto('${photo.name}', ${index})">
                    <img class="photo-image" src="/api/photo?file=${encodeURIComponent(photo.name)}"
                         alt="${photo.name}" onerror="this.src=''">
                    
                    ${
                      isVideoFile
                        ? `
                      <div class="video-indicator">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                          <polygon points="5,3 19,12 5,21"></polygon>
                        </svg>
                        Video
                      </div>
                    `
                        : ""
                    }
                    
                    <div class="file-type-badge ${isVideoFile ? "video" : ""}">
                      ${isVideoFile ? "Video" : "Image"}
                    </div>
                    
                    <div class="photo-info">
                        <div class="photo-name">${photo.name}</div>
                        <div class="photo-meta">
                            ${formatFileSize(photo.size)} • ${photo.modified}
                            ${isVideoFile ? " • 🎥 Video file" : ""}
                        </div>
                        <div class="photo-actions">
                            <button class="action-button view-button" onclick="event.stopPropagation(); viewPhoto('${photo.name}', ${index})">
                                ${isVideoFile ? "🎥 Play" : "👁️ View"}
                            </button>
                            <button class="action-button download-button" onclick="event.stopPropagation(); downloadPhoto('${photo.name}')">
                                ⬇️ Download
                            </button>
                        </div>
                    </div>
                </div>
            `
          })
          .join("")
      }

      // View a photo or video in modal
      function viewPhoto(filename, index) {
        const modal = document.getElementById("photoModal")
        const modalImage = document.getElementById("modalImage")

        const isVideo = currentGallery[index] && (currentGallery[index].is_video || false)
        const fileExtension = filename.split(".").pop().toLowerCase()
        const isVideoByExtension = ["mp4", "avi", "mov", "wmv", "flv", "webm", "mkv", "3gp"].includes(fileExtension)
        const isVideoFile = isVideo || isVideoByExtension

        if (isVideoFile) {
          // For videos, show thumbnail but provide download option
          modalImage.src = `/api/photo?file=${encodeURIComponent(filename)}`
          modalImage.alt = `Video thumbnail: ${filename}`

          // Add a note that this is a video thumbnail
          const videoNote = document.createElement("div")
          videoNote.className = "video-thumbnail-note"
          videoNote.innerHTML = `
            🎥 Video thumbnail • 
            <a href="/api/download?file=${encodeURIComponent(filename)}">
              Download Video
            </a>
          `
          modal.querySelector(".modal-content").appendChild(videoNote)
        } else {
          // For images, show the actual image
          modalImage.src = `/api/photo?file=${encodeURIComponent(filename)}`
          modalImage.alt = `Photo: ${filename}`
        }

        modal.style.display = "block"

        // Close modal when clicking outside
        modal.onclick = function (e) {
          if (e.target === modal) {
            closeModal()
          }
        }
      }

      // Close the modal
      function closeModal() {
        const modal = document.getElementById("photoModal")
        modal.style.display = "none"

        // Remove any video notes that were added
        const videoNotes = modal.querySelectorAll(".video-thumbnail-note")
        videoNotes.forEach(note => note.remove())
      }

      // Download a photo or video
      async function downloadPhoto(filename) {
        try {
          const response = await fetch(`/api/download?file=${encodeURIComponent(filename)}`)

          if (response.ok) {
            const blob = await response.blob()
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement("a")
            a.href = url
            a.download = filename
            document.body.appendChild(a)
            a.click()
            window.URL.revokeObjectURL(url)
            document.body.removeChild(a)

            const fileExtension = filename.split(".").pop().toLowerCase()
            const isVideo = ["mp4", "avi", "mov", "wmv", "flv", "webm", "mkv", "3gp"].includes(fileExtension)
            showToast(`Downloaded ${isVideo ? "video" : "photo"}: ${filename}`, "success")
          } else {
            throw new Error("Download failed")
          }
        } catch (error) {
          console.error("Error downloading file:", error)
          showToast("Failed to download file", "error")
        }
      }

      // Show toast notification
      function showToast(message, type = "success") {
        const toast = document.getElementById("toast")
        toast.textContent = message
        toast.className = `toast ${type}`
        toast.classList.add("show")

        setTimeout(() => {
          toast.classList.remove("show")
        }, 3000)
      }

      // Format file size
      function formatFileSize(bytes) {
        if (bytes === 0) return "0 Bytes"
        const k = 1024
        const sizes = ["Bytes", "KB", "MB", "GB"]
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
      }

      // Keyboard shortcuts
      document.addEventListener("keydown", function (e) {
        if (e.key === "Escape") {
          closeModal()
        }
        if (e.key === " " && !isCapturing) {
          e.preventDefault()
          takePicture()
        }
      })

      // Auto-refresh gallery every 30 seconds
      setInterval(loadGallery, 30000)
    </script>
  </body>
</html>
